<template>
  <div>
    <!-- 文章列表 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
    <van-list
  v-model="loading"
  :finished="finished"
  finished-text="没有更多了"
  offset='50'
  :immediate-check='false'
  @load="onLoad"
>
<article-item v-for="item in articlesList"
:key="item.art_id"
:Obj='item'></article-item>
    </van-list>
  </van-pull-refresh>
  </div>
</template>

<script>

import ArticleItem from './components/ArticleItem.vue'
import { articlesListAPI } from '@/api'
import { timeAgo } from '@/utils/date'
export default {
  components: { ArticleItem },
  props: {
    cid: { type: Number }
  },
  data () {
    return {
      articlesList: [],
      loading: false,
      finished: false,
      nextTime: null,
      isLoading: false
    }
  },
  methods: {
    timeAgo: timeAgo,
    onLoad () {
      // 最开始会出现数据重复 有了第一页数据以后，onLoad在发请求
      if (this.articlesList.length > 1) { this.getArticleList() }
    },
    onRefresh () {
      // 清空数据 元数据和第一页的时间戳
      this.articlesList = []
      this.nextTime = null
      // 再次调用接口请求数据
      this.getArticleList()
      // 讲下拉等待关闭
      this.isLoading = false
    },
    async getArticleList () {
      // 负责拿文章列表数据
      const res = await articlesListAPI({
        channelId: this.cid, // 默认推荐频道(id为0) // 传过来的id
        timestamp: this.nextTime // 加载更过（分页）
      })

      // 回来的数据进行预处理，把时间转换成多久多久之前
      res.data.data.results.forEach(item => {
        item.pubdate = this.timeAgo(item.pubdate)
      })
      // this.articlesList = res.data.data.results
      // 这里赋值会出问题 导致无限刷新
      // console.log(res.data.data.results)
      // 如果没有数据
      if (res.data.data.results.length === 0) {
        this.finished = true
      } else {
        this.nextTime = res.data.data.pre_timestamp // 保存下一页数据的时间
        this.articlesList = [...this.articlesList, ...res.data.data.results]
        // 等网络请求成功之后  底部加载更过状态  改为false
        this.loading = false
      }
    }
  },
  created () {
    this.getArticleList()
  }

}
</script>
